package com.dqp.cslggroup.Countdown;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;

import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.Util.CompressedBitmap;
import com.dqp.cslggroup.Util.GetTimeUtil;
import com.dqp.cslggroup.Util.ToastUtil;
import com.dqp.cslggroup.Util.UiUtils;
import com.dqp.cslggroup.bean.event;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class add_event extends BaseActivity {
    private EditText name, bz;
    private TextView content, count, date, msg, date_event;
    private RadioButton jnr, sr, dsr;
    private int select = 0;
    private int action;
    private Switch switchCompat;
    private AppCompatTextView ok;
    private String event_date, Date, del_name = "", event_bg;
    private ImageView img, big_bg;
    private event myevent = new event();
    private static String[] permissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_CALENDAR,
            Manifest.permission.WRITE_CALENDAR,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_event);
        Toolbar toolbar = findViewById(R.id.add_event_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        iniCamp();
        Intent intent = getIntent();
        action = intent.getIntExtra("action", 0);
        if (action == 1) {
            myevent = (com.dqp.cslggroup.bean.event) intent.getSerializableExtra("event");
            getdate();
            setDel();
        }
        add_events();
    }

    public void setDel() {
        Button del = findViewById(R.id.del_event);
        del.setVisibility(View.VISIBLE);
        del.setOnClickListener(v -> ToastUtil.showToast("长按删除｡◕ᴗ◕｡"));
        del.setOnLongClickListener(v -> {
            UiUtils.hideKeyboard(v);
            MyApplication.getDaoInstant().getEventDao().delete(myevent);
            finish();
            ToastUtil.showToast("删除成功｡◕ᴗ◕｡");
            return true;
        });
    }

    @SuppressLint("SetTextI18n")
    public void getdate() {
        String names = myevent.getName();
        String bzs = myevent.getBz();
        String dates = myevent.getDate();
        int zd = myevent.getZd();
        int sel = myevent.getSelect();
        String bg = myevent.getBg();
        Date d = new Date();
        @SuppressLint("SimpleDateFormat") DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String Date = df.format(d);
        name.setText(names);
        date.setText(dates);
        msg.setText(bzs);
        date_event.setText(dates);
        bz.setText(bzs);
        if (sel == 0) {
            jnr.setChecked(true);
            count.setText("第" + GetTimeUtil.addDates(dates, Date) + "天");
        } else if (sel == 1) {
            sr.setChecked(true);
            int counts = GetTimeUtil.addDates(Date, dates);
            if (counts > 0) {
                content.setText("距离" + names + "的生日还有");
                count.setText(counts + "天");
            } else {
                content.setText(names + "的生日已过去");
                count.setText(GetTimeUtil.addDates(dates, Date) + "天");
            }
        } else {
            dsr.setChecked(true);
            int counts = GetTimeUtil.addDates(Date, dates);
            if (counts > 0) {
                content.setText(names + "仅剩");
                count.setText(counts + "天");
            } else {
                content.setText(names + "已过去");
                count.setText(GetTimeUtil.addDates(dates, Date) + "天");
            }
        }
        if (CompressedBitmap.fileExist(bg))
            setbg(bg, names);
        if (zd == 1)
            switchCompat.setChecked(true);
        del_name = names;
        event_bg = bg;

    }

    @SuppressLint("SetTextI18n")
    public void iniCamp() {
        Date d = new Date();
        @SuppressLint("SimpleDateFormat") DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date = df.format(d);
        ok = findViewById(R.id.ok);
        jnr = findViewById(R.id.event_jnr);
        sr = findViewById(R.id.event_sr);
        dsr = findViewById(R.id.event_dsr);
        name = findViewById(R.id.et_event);
        bz = findViewById(R.id.et_msg);
        switchCompat = findViewById(R.id.s_fav);
        content = findViewById(R.id.tv_content);
        count = findViewById(R.id.tv_count);
        msg = findViewById(R.id.tv_msg);
        date = findViewById(R.id.tv_date);
        date_event = findViewById(R.id.et_date);
        date_event.setText(Date);
        AppCompatTextView bg = findViewById(R.id.add_event_bg);
        img = findViewById(R.id.iv_pic);
        big_bg = findViewById(R.id.iv_pic_bg);
        LinearLayout root_view = findViewById(R.id.root_event);
        RadioGroup radioGroup = findViewById(R.id.event_select);
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            if (jnr.isChecked()) {
                select = 0;
                if (name.getText().toString().isEmpty()) {
                    name.setHint("值得纪念的事情...");
                    content.setText("「」");
                } else {
                    content.setText(name.getText().toString());
                }
            } else if (sr.isChecked()) {
                select = 1;
                if (name.getText().toString().isEmpty()) {
                    name.setHint("寿星");
                    content.setText("「」生日还有");
                } else {
                    content.setText("距离" + name.getText().toString() + "的生日还有");
                }
            } else if (dsr.isChecked()) {
                select = 2;
                if (name.getText().toString().isEmpty()) {
                    name.setHint("事件");
                    content.setText("「」仅剩");
                } else {
                    content.setText(name.getText().toString() + "仅剩");
                }
            }
        });

        date_event.setOnClickListener(v -> {
            Dialog dialog;
            final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(add_event.this);
            @SuppressLint("InflateParams") View view = LayoutInflater.from(add_event.this).inflate(R.layout.date, null);
            builder.setView(view);
            final CalendarView calendarView = view.findViewById(R.id.date);
            dialog = builder.show();
            UiUtils.setDialogWindowAttr(dialog, add_event.this);
            Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(android.R.color.transparent);
            calendarView.setOnDateChangeListener((view1, year, month, dayOfMonth) -> {
                String months, days;
                month += 1;
                if (month < 10) {
                    months = "0" + month;
                } else months = Integer.toString(month);
                if (dayOfMonth < 10) {
                    days = "0" + dayOfMonth;
                } else days = Integer.toString(dayOfMonth);
                event_date = year + "-" + months + "-" + days;
                date.setText(event_date);
                date_event.setText(event_date);
                if (select == 0) {
                    count.setText("第" + GetTimeUtil.addDates(event_date, Date) + "天");
                } else if (select == 1) {
                    int counts = GetTimeUtil.addDates(Date, event_date);
                    if (counts > 0) {
                        content.setText("距离" + name.getText().toString() + "的生日还有");
                        count.setText(counts + "天");
                    } else {
                        content.setText(name.getText().toString() + "的生日已过去");
                        count.setText(GetTimeUtil.addDates(event_date, Date) + "天");
                    }
                } else {
                    int counts = GetTimeUtil.addDates(Date, event_date);
                    if (counts > 0) {
                        content.setText(name.getText().toString() + "仅剩");
                        count.setText(counts + "天");
                    } else {
                        content.setText(name.getText().toString() + "已过去");
                        count.setText(GetTimeUtil.addDates(event_date, Date) + "天");
                    }
                }
                dialog.dismiss();

            });
        });
        bz.addTextChangedListener(new TextWatcher() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                msg.setText(bz.getText().toString());
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                msg.setText(bz.getText().toString());
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void afterTextChanged(Editable s) {
                msg.setText(bz.getText().toString());
            }
        });

        name.addTextChangedListener(new TextWatcher() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (jnr.isChecked()) {
                    content.setText(name.getText().toString());
                } else if (sr.isChecked()) {
                    content.setText("距离" + name.getText().toString() + "的生日还有");
                } else if (dsr.isChecked()) {
                    content.setText(name.getText().toString() + "仅剩");
                }

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (jnr.isChecked()) {
                    content.setText(name.getText().toString());
                } else if (sr.isChecked()) {
                    content.setText("距离" + name.getText().toString() + "的生日还有");
                } else if (dsr.isChecked()) {
                    content.setText(name.getText().toString() + "仅剩");
                }

            }

            @SuppressLint("SetTextI18n")
            @Override
            public void afterTextChanged(Editable s) {
                if (jnr.isChecked()) {
                    content.setText(name.getText().toString());
                } else if (sr.isChecked()) {
                    content.setText("距离" + name.getText().toString() + "的生日还有");
                } else if (dsr.isChecked()) {
                    content.setText(name.getText().toString() + "仅剩");
                }

            }
        });

        bg.setOnClickListener(v -> {
            if (EasyPermissions.hasPermissions(this, permissions)) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, 1);
            } else new AppSettingsDialog.Builder(this)
                    .setTitle("权限申请")
                    .setRationale("您没有授权应用所需的读写手机存储的相关权限，此功能无法运行。请打开应用设置以修改应用权限。")
                    .build().show();
        });
        CardView cardView = findViewById(R.id.cv_event);
        cardView.setOnClickListener(v -> {
            if (EasyPermissions.hasPermissions(this, permissions)) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, 1);
            } else new AppSettingsDialog.Builder(this)
                    .setTitle("权限申请")
                    .setRationale("您没有授权应用所需的读写手机存储的相关权限，此功能无法运行。请打开应用设置以修改应用权限。")
                    .build().show();

        });

    }

    public void add_events() {
        ok.setOnClickListener(v -> {
            UiUtils.hideKeyboard(v);
            long size = MyApplication.getDaoInstant().getEventDao().count();
            if (size <= 10 || action != 0) {
                if (name.getText().toString().length() >= 1) {
                    if (switchCompat.isChecked()) {
                        List<event> eventList = MyApplication.getDaoInstant().getEventDao().queryBuilder()
                                .where(com.dqp.cslggroup.greendao.eventDao.Properties.Zd.eq(1))
                                .build()
                                .list();
                        if (eventList.size() > 0)
                            for (int i = 0; i < eventList.size(); i++) {
                                event events = eventList.get(i);
                                events.setZd(0);
                                MyApplication.getDaoInstant().getEventDao().update(events);
                            }
                        myevent.setZd(1);
                    } else myevent.setZd(0);
                    myevent.setName(name.getText().toString());
                    myevent.setBz(bz.getText().toString());
                    myevent.setDate(date_event.getText().toString());
                    myevent.setSelect(select);
                    myevent.setBg(event_bg);
                    if (myevent.getName() != null) {
                        if (action == 0) {
                            MyApplication.getDaoInstant().getEventDao().insertOrReplace(myevent);
                            ToastUtil.showToast("事件「" + myevent.getName() + "」添加成功 ٩(◕‿◕｡)۶");
                        } else {

                            MyApplication.getDaoInstant().getEventDao().update(myevent);
                            ToastUtil.showToast("事件「" + myevent.getName() + "」更新成功 ٩(◕‿◕｡)۶");
                        }
                        finish();
                    }
                } else ToastUtil.showToast("事件信息不完整 c༼ ” ͡° ▃ °͡ ” ༽ᕤ");
            } else ToastUtil.showToast("事件添加已到上限 c༼ ” ͡° ▃ °͡ ” ༽ᕤ");
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            assert selectedImage != null;
            @SuppressLint("Recycle") Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            assert cursor != null;
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            event_bg = cursor.getString(columnIndex);
        }
    }

    public void setbg(String path, String name) {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            if (path != null) {
                if (CompressedBitmap.fileExist(path)) {
                    Bitmap bitmap = BitmapFactory.decodeFile(path);
                    if (bitmap != null) {
                        bitmap = CompressedBitmap.Compressed(bitmap, 0.1f);
                        img.setImageBitmap(bitmap);
                        big_bg.setImageBitmap(bitmap);
                    } else if (name != null) {
                        event event = MyApplication.getDaoInstant().getEventDao().queryBuilder()
                                .where(com.dqp.cslggroup.greendao.eventDao.Properties.Name.eq(name))
                                .build()
                                .unique();
                        event.setBg(null);
                        MyApplication.getDaoInstant().getEventDao().update(event);
                        ToastUtil.showToast("照片已被移除，请重新设置！");
                    }
                } else if (name != null) {
                    event event = MyApplication.getDaoInstant().getEventDao().queryBuilder()
                            .where(com.dqp.cslggroup.greendao.eventDao.Properties.Name.eq(name))
                            .build()
                            .unique();
                    event.setBg(null);
                    MyApplication.getDaoInstant().getEventDao().update(event);
                    ToastUtil.showToast("照片已被移除，请重新设置！");
                }

            }
        } else new AppSettingsDialog.Builder(this)
                .setTitle("权限申请")
                .setRationale("您没有授权应用所需的读写手机存储的相关权限，此功能无法运行。请打开应用设置以修改应用权限。")
                .build().show();

    }


    @Override
    protected void onResume() {
        super.onResume();
        try {
            if (event_bg != null && (!event_bg.isEmpty()))
                setbg(event_bg, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
